package services

import (
	"errors"
	"stacks/database"
	"stacks/models"
)

// PermissionService 权限服务
type PermissionService struct{}

// NewPermissionService 创建权限服务实例
func NewPermissionService() *PermissionService {
	return &PermissionService{}
}

// GetPermissionByID 根据ID获取权限
func (s *PermissionService) GetPermissionByID(id, tenantID uint) (*models.SysPermission, error) {
	var permission models.SysPermission
	err := database.GetDB().Where("id = ? AND tenant_id = ?", id, tenantID).First(&permission).Error
	if err != nil {
		return nil, errors.New("权限不存在")
	}
	return &permission, nil
}

// GetPermissionList 获取权限列表
func (s *PermissionService) GetPermissionList(tenantID uint, page, pageSize int) ([]models.SysPermission, int64, error) {
	var permissions []models.SysPermission
	var total int64

	db := database.GetDB().Where("tenant_id = ?", tenantID)
	db.Model(&models.SysPermission{}).Count(&total)

	offset := (page - 1) * pageSize
	err := db.Offset(offset).Limit(pageSize).Find(&permissions).Error
	if err != nil {
		return nil, 0, err
	}

	return permissions, total, nil
}

// CreatePermission 创建权限
func (s *PermissionService) CreatePermission(permission *models.SysPermission) error {
	// 检查权限码是否已存在
	var existingPermission models.SysPermission
	err := database.GetDB().Where("code = ? AND tenant_id = ?", permission.Code, permission.TenantID).First(&existingPermission).Error
	if err == nil {
		return errors.New("权限码已存在")
	}

	return database.GetDB().Create(permission).Error
}

// UpdatePermission 更新权限
func (s *PermissionService) UpdatePermission(id, tenantID uint, updates map[string]interface{}) error {
	var permission models.SysPermission
	err := database.GetDB().Where("id = ? AND tenant_id = ?", id, tenantID).First(&permission).Error
	if err != nil {
		return errors.New("权限不存在")
	}

	// 检查权限码是否重复
	if code, ok := updates["code"].(string); ok {
		var existingPermission models.SysPermission
		err = database.GetDB().Where("code = ? AND tenant_id = ? AND id != ?", code, tenantID, id).First(&existingPermission).Error
		if err == nil {
			return errors.New("权限码已存在")
		}
	}

	return database.GetDB().Model(&permission).Updates(updates).Error
}

// DeletePermission 删除权限
func (s *PermissionService) DeletePermission(id, tenantID uint) error {
	var permission models.SysPermission
	err := database.GetDB().Where("id = ? AND tenant_id = ?", id, tenantID).First(&permission).Error
	if err != nil {
		return errors.New("权限不存在")
	}

	return database.GetDB().Delete(&permission).Error
}
